package com.lsh.controller;

import com.lsh.constants.RedisMessageConstant;
import com.lsh.entity.Result;
import com.lsh.utils.RedisStringUtils;
import com.lsh.utils.TencentSMSUtils;
import com.lsh.utils.ValidateCodeUtils;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    private RedisStringUtils redisStringUtils;
    @PostMapping("/send4Order")
    public Result send4Order(@RequestParam("telephone") String phone){
        //发送验证码之前，先查询是否发送过了
        if(!redisStringUtils.hasKey(RedisMessageConstant.SEND_SENDSTATUS + phone)){
            //不存在发送记录，生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            //发送验证码
            try {
                TencentSMSUtils.sendSms(phone,new String[]{code+""});
                //发送成功,验证码存入redis，设置过期时间10分钟
                redisStringUtils.set(RedisMessageConstant.SEND_KEYSTATUS+phone,code+"",600);
                //发送状态存入redis设置过期时间60秒
                redisStringUtils.set(RedisMessageConstant.SEND_SENDSTATUS + phone,code+"",60);
                return new Result(true,"验证码发送成功");
            } catch (TencentCloudSDKException e) {
                e.printStackTrace();
                return new Result(false,"系统错误，联系管理员");
            }
        }
        return new Result(false,"验证码发送过快，请等待60秒在重新发送");
    }
}
